"""
    TorrentBrowser plugin for XBMC
    Copyright (C) 2011-2012 Markus Langenoja
    
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
    
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
    
    Function [TBWeb]
    ------------------
    * loginOpen(url) - Logins to torrentsite and opens url
    * webOpen(url) - Opens url
    * buildCookie() - Creates cookie for web
    * loginCookie() - Creates a logged in cookie for torrentsite
    * checkCookie() - Checks if saved cookies is older then 1 hour
"""
import sys, os, time, urllib, re
import TBTools
from cookielib import LWPCookieJar
from urllib2 import build_opener, install_opener, HTTPCookieProcessor
from xbmc import translatePath

class TBWeb(TBTools.TBTools):
    __deb__ = sys.modules[ "__main__" ].__deb__
    __plugin__ = sys.modules[ "__main__" ].__plugin__
    __settings__ = sys.modules[ "__main__" ].__settings__
    __info__ = sys.modules[ "__main__" ].__info__
    
    uname = __settings__.getSetting('username')
    upass = __settings__.getSetting('password')
    site = __settings__.getSetting('site')
    
    def loginOpen(self, url):
        ''' Test if cookie is there and not older then 1 hour, else build new cookie '''
        initTime = time.time()
        self.checkCookie()
        
        src = self.__opener__.open(url)
        data = src.read()
        src.close()
        
        ''' Check if logged in, if it fails, removes cookie and open settings '''
        regExp = self.__info__['FAILED']
        if re.search(regExp, data):
            self.showOK('Login Failed', 'Username/Password Wrong')
            self.__settings__.openSettings()
            os.remove(self.__cookie__)
            return self.loginOpen(url)
            
        if self.__deb__:
            print self.__plugin__ + '::DEBUG::TBWeb::' + 'loginOpen completed'
            
        return data
    
    def webOpen(self, url):
        self.buildCookie()
        src = self.__opener__.open(url)
        data = src.read()
        src.close()
        if self.__deb__:
            print self.__plugin__ + '::DEBUG::TBWeb::' + 'webOpen completed'
        return data
        
    def buildCookie(self):
        # Create cookie jar and build & install the opener
        self.__cj__ = LWPCookieJar()
        self.__opener__ = build_opener(HTTPCookieProcessor(self.__cj__))
        install_opener(self.__opener__)
        if self.__deb__:
            print self.__plugin__ + '::DEBUG::TBWeb::' + 'buildCookie completed'
        return self.__cj__
    
    def loginCookie(self,__cookie__):
        # Build cookie
        self.buildCookie()
        
        # Extract site specific parameters
        upost = self.__info__['POSTUSER']
        ppost = self.__info__['POSTPASS']
        loginUrl = self.__info__['LOGINURL']
        if self.__deb__:
            print self.__plugin__ + '::DEBUG::TBWeb::' + 'logging in via: ' + loginUrl
        # Build the POST data from the login page and open the loginUrl together with POST data, thus logging in.
        loginData = urllib.urlencode({upost:self.uname,ppost:self.upass})
        page = self.__opener__.open(loginUrl, loginData)
        page.close()
            
        self.__cj__.save(__cookie__, ignore_discard=True)
        
        if self.__deb__:
            print self.__plugin__ + '::DEBUG::TBWeb::' + 'loginCookie'
        
        # Returns the initiated opener containing "logged in" cookies    
        return self.__opener__
    
    def checkCookie(self):
        __hourold__ = time.time() - 3600
        self.__cookie__ = os.path.join(translatePath( "special://temp" ), "cookie.lwp")
        
        if os.path.exists(self.__cookie__):
            # Cookie exists
            if os.path.getmtime(self.__cookie__) < __hourold__:
                # Cookie is older then one hour, create new one
                os.remove(self.__cookie__)
                self.loginCookie(self.__cookie__)
                return
            else:
                # Load cookie if not older then one hour
                self.buildCookie()
                self.__cj__.load(self.__cookie__, ignore_discard=True)
                return
        else:
            # If the cookie doesn't exist, create it
            self.loginCookie(self.__cookie__)
            return   
